<template>
  <div class="h-100">
    <div>
      <div class="header fillinfo-modal">
        <a-form>
          <a-form-item :label="$t('label.time_filter')">
            <a-range-picker
              :show-time="{ format: 'HH:mm:ss' }"
              format="YYYY-MM-DD HH:mm:ss"
              :placeholder="['Start Time', 'End Time']"
              @change="onRangeChange"
            />
          </a-form-item>
          <a-form-item :label="$t('label.search')" class="flex-1">
            <div class="search-item">
              <a-input
                :placeholder="$t('placeholder.profile_to_order_search')"
                v-model:value="serachForm.keyword"
              ></a-input>
              <a-button
                style="background: #13c29c"
                type="primary"
                @click="onClicksearchBtn"
                >{{ $t("btnText.search_query") }}</a-button
              >
            </div>
          </a-form-item>
        </a-form>
      </div>
      <div class="pc-table">
        <Table
          size="small"
          striped
          theadBgColor="#e6edf2"
          index
          :index-length="3"
          :data="TaskData"
          :columns="taskOrderColumns"
          :operate="{
            width: '10.4167vw',
          }"
        >
          <template #status="{ row }">
            <div
              class="status success"
              v-if="row.status == 3 || row.status == 4"
            >
              {{ row.status_title }}
            </div>
            <div
              class="status danger"
              v-if="row.status == 1 || row.status == 2"
            >
              {{ row.status_title }}
            </div>
          </template>
          <template #operate="{ row }">
            <div class="operate">
              <div class="btn" @click="getTaskDetailData(row.id)">
                <IconDetail />
                <span>{{ $t("btnText.detail") }}</span>
              </div>
              <template v-if="!row._rawData.receive_last_name">
                <span>|</span>
                <div class="btn" @click="allocateBtn(row)">
                  <IconAllocate />
                  <span>{{ $t("btnText.allocate") }}</span>
                </div>
              </template>
            </div>
          </template>
        </Table>
      </div>
      <TaskMobile
        @getTaskDetailData="getTaskDetailData"
        @followUp="allocateBtn"
        :data="TaskData"
        allocate
      />
    </div>

    <div class="show_more_container">
      <ShowMore
        pagerMb="0"
        v-model:currentPage="listParams.page"
        :totalCount="listParams.total"
        @change="getProfileTaskData"
      />
    </div>
  </div>
  <!-- 任务详情 -->
  <DialogTaskDetail ref="dialogTaskDetailRef" :id="task_id" />
  <!-- 任务分配 -->
  <DialogTaskToOrder
    ref="dialogTaskToOrderRef"
    @allocate-success="getProfileTaskData"
    :list="orderUserList"
    :id="task_id"
    :orderDetail="orderDetail"
  />
</template>

<script setup  lang="ts">
import { defineAsyncComponent, getCurrentInstance, nextTick, ref } from "vue";
import type { TaskItem } from "../../../../types/task";
import { postMemberTaskList, postTaskOrderList } from "../../../../api/task";
import { taskOrderColumns } from "../a_data/table";
const Table = defineAsyncComponent(() => import("../a_components/table"));
const TaskMobile = defineAsyncComponent(() => import("./taskMobile.vue"));
const TaskData = ref<TaskItem[]>();

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

let cacheTaskData: any = null;
const listParams = ref({
  page: 1,
  total: 0,
});

const padIndex = (index: number) => {
  return index.toString().padStart(3, "0");
};

const getProfileTaskData = async () => {
  TaskData.value = undefined;
  let status = 2;
  let page = listParams.value.page;
  let res = await postMemberTaskList({ status, page });
  if (res.code === 200) {
    TaskData.value = res.data.data.map((item, index) => {
      return {
        ...item,
        index: padIndex(index + 1),
        publisher: item.member_last_name +' '+ item.member_first_name,
        receiver: item.receive_last_name + ' '+ item.receive_first_name,
        time: item.create_time,
        _rawData: item,
      };
    });
    listParams.value.total = res.data.total;
    cacheTaskData = JSON.parse(JSON.stringify(TaskData.value));
  }
};
getProfileTaskData();

// 查询数据
const serachForm = ref<{
  keyword: string;
  time_range: [string, string] | [];
}>({
  keyword: "",
  time_range: [],
});
const onRangeChange = (value: any, dateString: [string, string]) => {
  serachForm.value.time_range = dateString;
};

const onClicksearchBtn = () => {
  let keyword = serachForm.value.keyword;
  let time_filter = serachForm.value.time_range[0] ? true : false;
  const filterDataClone = JSON.parse(JSON.stringify(cacheTaskData));
  TaskData.value! = filterDataClone.filter((item) => {
    let publisher_name = item.publisher;
    let receiver_name = item.receiver;
    let date_range = true;
    if (time_filter) {
      date_range =
        new Date(serachForm.value.time_range[0]!).getTime() <=
          new Date(item.time).getTime() &&
        new Date(item.time).getTime() <=
          new Date(serachForm.value.time_range[1]!).getTime();
    }
    if (
      (publisher_name.includes(keyword) || receiver_name.includes(keyword)) &&
      date_range
    )
      return item;
  });
};

// =============任务详情 =================
const task_id = ref();
const dialogTaskDetailRef = ref();
const getTaskDetailData = async (id: number) => {
  if (isMobile()) {
    goto("/mobile_detail/task", { id });
    return;
  }
  task_id.value = id;
  nextTick(() => {
    dialogTaskDetailRef.value.showDialog();
  });
};

// 分配
const orderDetail = ref();
const orderUserList = ref();
const dialogTaskToOrderRef = ref();
const allocateBtn = async (item: TaskItem) => {
  let taskId = item.id;
  // 有数据且id相同直接弹窗
  if (
    orderUserList.value &&
    orderUserList.value.length > 0 &&
    taskId == task_id.value
  ) {
    if (isMobile()) {
      sessionStorage.setItem("taskDetailData", JSON.stringify(item));
      goto("/mobile/allocate");
      return;
    }
    dialogTaskToOrderRef.value.showDialog();
    return;
  }
  // 判断是否有分配的人员
  let res = await postTaskOrderList(taskId);
  task_id.value = taskId;
  orderDetail.value = item;
  // 无分配人员
  orderUserList.value = res.data || [];
  if (orderUserList.value.length == 0) {
    message.error("暂无可分配人员");
    return;
  }
  if (isMobile()) {
    sessionStorage.setItem("taskDetailData", JSON.stringify(item));
    goto("/mobile/allocate");
    return;
  }
  // 有分配人员
  nextTick(() => {
    dialogTaskToOrderRef.value.showDialog();
  });
};
</script>
<style scoped lang="less">
.operate {
  display: flex;
  align-items: center;
  .btn {
    display: flex;
    align-items: center;
    white-space: nowrap;
    gap: 4px;
    padding: 0;
    font-size: 16px;
  }
  & > span {
    color: #ccd6de;
    margin: 0 10px;
  }
}

.header {
  margin-bottom: 0;
  :deep(.ant-form) {
    display: flex;
    gap: 50px;
    .search-item {
      display: flex;
      gap: 30px;
      .ant-input {
        min-width: 100px;
      }
    }
    .ant-picker {
      input {
        @media screen and (min-width: 768px) {
          font-size: 18px !important;
        }
      }
    }
    .ant-form-item {
      margin-bottom: 24px;
    }
    .ant-form-item-label {
      display: flex;
      align-items: center;
    }
    .ant-form-item.flex-1 {
      max-width: 400px;
    }
  }
  .nav {
    height: 25px;
  }
  .ant-btn {
    height: 40px !important;
    border-radius: 12px !important;
    font-size: 14px !important;
  }
}

.h-100 {
  display: flex;
  flex-direction: column;
  & > div:first-child {
    flex: 1;
  }
}
@media screen and (max-width: 768px) {
  .show_more_container {
    background-color: #f6f8fa;
    margin-left: -82px;
    margin-right: -82px;
  }
  .pc-table {
    display: none;
  }
  .header {
    margin-bottom: 123px;
    .ant-btn {
      height: 205px !important;
      padding: 51px 123px !important;
      border-radius: 61px !important;
      font-size: 72px !important;
    }

    :deep(.ant-form) {
      flex-direction: column;
      .ant-form-item {
        max-width: 100% !important;
      }
      .ant-form-item-label label {
        font-size: 72px;
      }
      .ant-form-item-control-input {
        .ant-form-item-control-input-content,
        .ant-picker {
          height: 100%;
        }
      }
      input {
        font-size: 72px !important;
      }
      .search-item {
        gap: 82px;
        align-items: center;
        input {
          flex: 1;
        }
        .ant-btn {
          height: 100% !important;
        }
      }
    }
  }
}
</style>